﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Contracts;
using Events;
using ViewModel;
using Application=System.Windows.Application;

namespace View
{
	/// <summary>
	/// Logique d’interaction pour Window1.xaml
	/// </summary>
	public partial class Window1 : Window
	{
        private NotifyIcon trayNotifyIcon;
        protected MainViewModel ViewModel { get; set; }
        
        /// <summary>
        /// Class Constructor.
        /// Create the Main View Model, and listen some events on it
        /// </summary>
		public Window1()
		{
            // Initialize the component
			this.InitializeComponent();
            ViewModel = new MainViewModel();
		    DataContext = ViewModel;

            // Listen to some events
		    MainViewModel.OnUserConnected += OnUserConnected;

            // Create the icon to the systray
            trayNotifyIcon = new NotifyIcon();
		    trayNotifyIcon.Text = "Kikoo Instant Messenger!";
            trayNotifyIcon.Icon = new System.Drawing.Icon("Application.ico");
            trayNotifyIcon.Visible = true;
            trayNotifyIcon.DoubleClick += mnuOpen_Click;
            ContextMenuStrip ctxTrayMenu = new ContextMenuStrip();
            ToolStripMenuItem mnuOpen = new ToolStripMenuItem();
            mnuOpen.Text = "Open KIM";
            mnuOpen.Click += mnuOpen_Click;
            ctxTrayMenu.Items.Add(mnuOpen);
            ToolStripMenuItem mnuExit = new ToolStripMenuItem();
            mnuExit.Text = "Exit";
            mnuExit.Click += mnuExit_Click;
            ctxTrayMenu.Items.Add(mnuExit);
            trayNotifyIcon.ContextMenuStrip = ctxTrayMenu;

            MenuItemChangeAvatar.IsEnabled = false;
            MenuItemChangeAvatar.Foreground = Brushes.Gray;
		}

        /// <summary>
        /// Method called when the user is succefully connected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnuExit_Click(object sender, EventArgs e)
        {
            this.trayNotifyIcon.Visible = false;
            Application.Current.Shutdown();
        }

        private void mnuOpen_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void OnUserConnected(object sender, RoutedEventArgs e)
        {
           
            MainViewModel.OnImageUpdated += UpdateAvatar;
            Storyboard sb = this.FindResource("OnUserConnected") as Storyboard;
            sb.Begin();
            this.windowDiscussion = new WindowDiscussion();
            MainViewModel.OnShowDiscussionContainer += StartDiscussion;
            menuItemDeconnexion.IsEnabled = true;
            menuItemDeconnexion.Foreground = Brushes.White; 
            MenuItemChangeAvatar.IsEnabled = true;
            MenuItemChangeAvatar.Foreground = Brushes.Black;

            MainViewModel.OnContactUpdated += this.systrayNotify;

        }

        /// <summary>
        /// Creates the windows discussion container.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartDiscussion(object sender, EventArgs e)
	    {
            if (this.windowDiscussion != null)
            {
                //this.windowDiscussion.Show();
            }
            //MainViewModel.OnShowDiscussionContainer -= StartDiscussion;
	    }

	    private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            menuItemDeconnexion.IsEnabled = false;
            menuItemDeconnexion.Foreground = Brushes.Gray;
        }

        private void menuItemDeconnect_Click(object sender, RoutedEventArgs e)
        {
            // Logout
            this.ViewModel.Logout();

            // Change the view
            menuItemDeconnexion.IsEnabled = false;
            menuItemDeconnexion.Foreground = Brushes.Gray;
            MenuItemChangeAvatar.IsEnabled = false;
            MenuItemChangeAvatar.Foreground = Brushes.Gray;

            if (windowDiscussion.IsLoaded.Equals(true))
                windowDiscussion.Close();
        }

        private void systrayNotify(object sender, TextEventArgs e)
        {
            this.trayNotifyIcon.ShowBalloonTip(3000, "KIM", e.Text, new ToolTipIcon());
        }

        private void MenuItemChangeAvatar_Click(object sender, RoutedEventArgs e)
        {
            ImageSource imgSrcTmp = imageAvatar.Source;
            imageAvatar.Source = null;
            new WindowChangeAvatar(this.ViewModel).ShowDialog();
            if (this.ViewModel.Img != null)
            {
                //Récupération de l'imageSource
                //imageAvatar.Source = (ImageSource) new ImageSourceConverter().ConvertFromString("Avatar.jpg");

                //temp
                imageAvatar.Source = this.ViewModel.Img;
            }
            else
            {
                imageAvatar.Source = imgSrcTmp;
            }
        }

	    private void UpdateAvatar(object sender, EventArgs e)
	    {
            this.imageAvatar.Source = this.ViewModel.Img;
	    }

	    WindowDiscussion windowDiscussion ;

        private void listBoxContacts_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Contact selectedContact = listBoxContacts.SelectedItem as Contact;
            if (selectedContact == null)
                return;

            this.ViewModel.SelectContactCommand.Execute(selectedContact);
            
            try
            {
                if (windowDiscussion == null || windowDiscussion.IsLoaded == false)
                {
                    windowDiscussion = new WindowDiscussion();
                }
                windowDiscussion.Show();

                //bool tabAlreadyExist = false;
                //foreach (DiscussionViewModel tabs in windowDiscussion.tabControlDiscussion.Items)
                //{
                //    if (tabs.CurrentContact.Equals(selectedContact))
                //    {
                //        tabAlreadyExist = true;
                //        windowDiscussion.tabControlDiscussion.SelectedItem = tabs;
                //    }
                //}
                //if (!tabAlreadyExist)
                //{
                //    TabItem tabItem = new ContactTabItem(selectedContact);
                //    windowDiscussion.tabControlDiscussion.Items.Add(tabItem);
                //    windowDiscussion.tabControlDiscussion.SelectedItem = tabItem;
                //}
            }
            catch (NullReferenceException){}
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // Instead of shuting down, hide the app in the systray
            e.Cancel = true;
            this.Hide();
        }

        private void addContact()
        {
            new WindowAddContact().ShowDialog();
            this.ViewModel.RefreshContactList();
        }

        private void editContact()
        {
            Contact selectedContact = listBoxContacts.SelectedItem as Contact;
            if (selectedContact == null)
                return;

            WindowAddContact win = new WindowAddContact();
            win.SetContact(selectedContact);
            win.ShowDialog();
            this.ViewModel.RefreshContactList();
        }

        private void deleteContact()
        {
            Contact selectedContact = listBoxContacts.SelectedItem as Contact;
            if (selectedContact == null)
                return;

            string msg = string.Format("Do you really want to remove '{0}' from your contact list ?", selectedContact.Mail);
            DialogResult dr = System.Windows.Forms.MessageBox.Show(msg, "KIM - Confirmation", MessageBoxButtons.YesNo);

            if (dr.Equals(System.Windows.Forms.DialogResult.Yes))
                this.ViewModel.DeleteContact(selectedContact);
        }

        private void buttonAddContact_Click(object sender, RoutedEventArgs e)
        {
            this.addContact();
        }

        private void buttonDeleteContact_Click(object sender, RoutedEventArgs e)
        {
            this.deleteContact();
        }

        private void mnuAddContact_Click(object sender, RoutedEventArgs e)
        {
            this.addContact();
        }

        private void mnuEditContact_Click(object sender, RoutedEventArgs e)
        {
            this.editContact();
        }

        private void mnuDeleteContact_Click(object sender, RoutedEventArgs e)
        {
            this.deleteContact();
        }

	}
}